from django.shortcuts import render_to_response
from myapp.models import Announcement, Location, User, AnnouncementForm
from django.contrib.auth.decorators import login_required
from myapp.helpers import *
from django.shortcuts import redirect
from datetime import *
from django.db.models import Count, Max

# Create your views here.
def index(request):
    top_schools = Location.tree.all().annotate(post_count = Count('announcement')).annotate(last_post = Max('announcement__pub_date')).order_by('-post_count')[:5]
    latest_posts = Announcement.objects.all().order_by('-pub_date')[:3]
    # latest_posts = pagination_helper(request, latest_posts) 	
    return render_to_response('index.html', { 'latest_posts': latest_posts, 'top_schools': top_schools })
    
def search(request):
    locations = Location.tree.all()
    announcements = Announcement.objects.filter(text__icontains=request.GET['q'])    
    announcements = pagination_helper(request, announcements)    
    return render_to_response('index.html', { 'announcements': announcements, 'locations': locations})
    
def location(request, location_slug):
    locations = Location.tree.all()
    location = Location.objects.get(slug=location_slug)
    posts = Announcement.objects.filter(location=location)        
    posts = pagination_helper(request, posts)    
    return render_to_response('location.html', { 'posts': posts, 'location': location , 'locations': locations})

@login_required    
def user(request, user_name):
    locations = Location.tree.all()
    user = User.objects.get(username=user_name)
    announcements = Announcement.objects.filter(user=user)
    announcements = pagination_helper(request, announcements)
    return render_to_response('user.html', { 'user': user, 'announcements': announcements, 'locations': locations })

@login_required 
def announcement_add(request):
    if request.method == 'POST': # If the form has been submitted...
        form = AnnouncementForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass            
            announcement = form.save(commit=False)
            announcement.user = request.user
            announcement.pub_date=datetime.now()
            announcement.votes=0
            announcement.save()
            location = form.cleaned_data['location']            
            return redirect('myapp.views.location',location_slug = location.slug) # Redirect after POST
    else:
        form = AnnouncementForm() # An unbound form

    return render_to_response('announcement_add.html', {
        'form': form,
    })    

def announcement_vote_add(request, announcement_id):
    announcement = Announcement.objects.get(pk=announcement_id)
    announcement.votes += 1
    announcement.save()
    return render_to_response('announcement_vote_add.html', {'announcement' : announcement})
    